from django.test import TestCase
from django.contrib.auth.models import User
from django.urls import reverse
from .models import Category, Post, Comment


class BlogModelTests(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(
            username='testuser',
            email='test@example.com',
            password='testpass123'
        )
        self.category = Category.objects.create(
            name='测试分类',
            description='这是一个测试分类'
        )
    
    def test_category_creation(self):
        self.assertEqual(str(self.category), '测试分类')
    
    def test_post_creation(self):
        post = Post.objects.create(
            title='测试文章',
            slug='test-post',
            content='这是测试内容',
            author=self.user,
            category=self.category,
            status='published'
        )
        self.assertEqual(str(post), '测试文章')
        self.assertEqual(post.get_absolute_url(), '/blog/post/test-post/')
    
    def test_comment_creation(self):
        post = Post.objects.create(
            title='测试文章',
            slug='test-post',
            content='这是测试内容',
            author=self.user,
            category=self.category,
            status='published'
        )
        comment = Comment.objects.create(
            post=post,
            author=self.user,
            content='这是测试评论'
        )
        self.assertIn('测试评论', str(comment))


class BlogViewTests(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(
            username='testuser',
            email='test@example.com',
            password='testpass123'
        )
        self.category = Category.objects.create(
            name='测试分类',
            description='这是一个测试分类'
        )
        self.post = Post.objects.create(
            title='测试文章',
            slug='test-post',
            content='这是测试内容',
            author=self.user,
            category=self.category,
            status='published'
        )
    
    def test_post_list_view(self):
        response = self.client.get(reverse('blog:post_list'))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, '测试文章')
    
    def test_post_detail_view(self):
        response = self.client.get(reverse('blog:post_detail', kwargs={'slug': 'test-post'}))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, '测试文章')
    
    def test_post_create_view_requires_login(self):
        response = self.client.get(reverse('blog:post_create'))
        self.assertEqual(response.status_code, 302)  # 重定向到登录页面